import React, { useEffect, useRef, useState } from 'react';
import { defaultsDeep } from 'lodash';
import { customizeValidator, Localizer } from '@rjsf/validator-ajv8';
import { AmcaxForm } from '@amcax/base';
import i18n from 'i18next';
import cx from 'classnames';
import { RegistryFieldsType, RegistryWidgetsType, UiSchema } from '@rjsf/utils';
import { FormFooter } from './FormFooter';
import {
  SelectionField,
  TabsField,
  InputField,
  VectorInputField,
} from '../../ui';
import { DialogProps } from './types';
import { MultipleChoice } from '../../ui/SelectionField/multipleChoice';
import { SwitchArr } from '../../ui/SwitchArr';
import { AutoCompleteField } from '../../ui/AutoComplete';
import { ButtonField } from '../../ui/Button';
import { CheckBoxInpArr } from '../../ui/CheckBoxInpArr';
import { ButtonArrField } from '../../ui/Button/btnArr';
import { ButtonGroupField } from '../../ui/ButtonGroupField';
import { CollapseTemplate } from '../../ui/CollapseTemplate';
import { InputSelectField } from '../../ui/InputSelectField';
import { StructureCardFields } from '../../ui/StructureField';
import { RelatedSelect } from '../../ui/SelectionField/relatedSelect';
import { TableField } from '../../ui/TableField';
import './formContent.scss';

export const FormContent = ({
  submitText = '确认',
  onClose,
  extraUiSchema,
  validator,
  fields,
  widgets,
  templates,
  description,
  disabled,
  onSubmit,
  onPreview,
  formClassName,
  footerChildren,
  showCancel = true,
  showSubmit = true,
  submitLoading = false,
  previewLoading = false,
  isFormDataValid = true,
  ...rest
}: DialogProps) => {
  // 如果preview响应很快，那么ui上就不会看到一闪而过的loading，响应超过200ms才会看到loading
  // 但是ui上看不到loading时，也还是会正常阻止onPreview触发
  const uiPreviewLoadingTimer = useRef<NodeJS.Timeout>();
  // 逻辑上是否loading
  const previewLoadingRef = useRef(previewLoading);
  const [uiPreviewLoading, setUiPreviewLoading] = useState(false);

  useEffect(() => {
    if (previewLoading) {
      previewLoadingRef.current = true;
      uiPreviewLoadingTimer.current = setTimeout(() => {
        setUiPreviewLoading(true);
      }, 200);
    } else {
      previewLoadingRef.current = false;
      clearTimeout(uiPreviewLoadingTimer.current);
      uiPreviewLoadingTimer.current = null;
      setUiPreviewLoading(false);
    }
  }, [previewLoading]);

  const uiSchema: UiSchema = defaultsDeep(
    { ...extraUiSchema },
    {
      'ui:options': {
        description,
        classNames: 'command-form',
        submitButtonOptions: {
          norender: true,
        },
      },
    },
  );

  // 自定义Fields组件注入
  const customizeFields: RegistryFieldsType = {
    tabsField: TabsField,
    selectionField: SelectionField,
    inputField: InputField,
    vectorInputField: VectorInputField,
    multipleChoice: MultipleChoice,
    switchArr: SwitchArr,
    autoCompleteField: AutoCompleteField,
    buttonField: ButtonField,
    checkBoxInpArr: CheckBoxInpArr,
    buttonArrField: ButtonArrField,
    buttonGroupField: ButtonGroupField,
    inputSelectField: InputSelectField,
    StructureCardFields: StructureCardFields,
    relatedSelect: RelatedSelect,
    tableField: TableField,
  };

  // 自定义Widgets组件注入
  const customizeWidgets: RegistryWidgetsType = {};

  // 自定义Template组件注入
  const customizeTemplate = { CollapseTemplate };

  // 信息提示
  const getMessage = (
    defaultMsg: string,
    keyword: string,
    param: Record<string, any>,
  ) => {
    const key = `validation.${keyword}`;
    const msg = i18n.t(key, param);
    return msg === key ? defaultMsg : msg.toString();
  };

  // 自定义校验，对错误信息进行i18n
  const localizer: Localizer = (errors) => {
    errors?.forEach((e) => {
      if (!e || !e.keyword || !e.message) {
        return;
      }
      let keyword = e.keyword;
      switch (keyword) {
        case 'required':
          e.message = getMessage(e.message, keyword, e.params);
          break;
        case 'type':
          // e.message = '必须是 数字';
          // e.stack = ''尺寸' 必须是 数字';
          e.message = getMessage(e.message, keyword, {
            type: i18n.t(e.params?.type),
          });
          break;
        case 'exclusiveMinimum':
          e.message = getMessage(e.message, keyword, e.params);
          break;
        case 'minItems':
          // 选取的是实体，特殊处理一下
          if (e.schemaPath?.includes('SelectedEntities')) {
            keyword = 'entityMinItems';
          }
          e.message = getMessage(e.message, keyword, e.params);
          break;
        case 'maxItems':
          // 选取的是实体，特殊处理一下
          if (e.schemaPath?.includes('SelectedEntities')) {
            keyword = 'entityMaxItems';
          }
          e.message = getMessage(e.message, keyword, e.params);
          break;
        case 'pattern':
          e.message = getMessage(e.message, keyword, {
            pattern: i18n.t(e.params?.pattern),
          });
          break;
      }
      return;
    });
  };

  // 自定义校验，对错误信息进行i18n
  const defaultValidator = customizeValidator(undefined, localizer);
  return (
    <AmcaxForm
      validator={validator ?? defaultValidator}
      fields={{ ...fields, ...customizeFields }}
      widgets={{
        ...widgets,
        ...customizeWidgets,
      }}
      {...rest}
      className={cx('rjsf', formClassName, disabled && 'rjsf-disabled')}
      disabled={disabled ?? submitLoading}
      uiSchema={uiSchema}
      templates={{
        ...templates,
        ...customizeTemplate,
      }}
      onSubmit={({ formData }) => onSubmit?.(formData)}>
      {footerChildren ?? (
        <FormFooter
          disabled={disabled}
          showCancel={showCancel}
          showPreview={onPreview != null}
          showSubmit={showSubmit}
          onClose={onClose}
          onPreview={() => {
            if (previewLoadingRef.current) {
              return;
            }
            onPreview?.();
          }}
          isPreviewLoading={uiPreviewLoading}
          isSubmitLoading={submitLoading}
          isPreviewDisabled={!isFormDataValid}
          isSubmitDisabled={!isFormDataValid}
          submitText={submitText}
        />
      )}
    </AmcaxForm>
  );
};
